package com.zh.controller;

import com.zh.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.fileBasePath}")
    private String BASE_PATH;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        log.info("文件上传:{}", file.toString());
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        file.transferTo(new File(BASE_PATH + newFileName));
        log.info("文件上传成功:{}", newFileName);
        return Result.success(newFileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        log.info("文件下载:{}", name);
        URLEncoder.encode(name, StandardCharsets.UTF_8);
        FileInputStream fileInputStream = new FileInputStream(BASE_PATH + name);
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
        response.setHeader("Content-Length", String.valueOf(fileInputStream.available()));
        response.setHeader("Content-Type", "multipart/form-data");
        response.setContentType("image/jpeg");
        IOUtils.copy(fileInputStream, outputStream);
        outputStream.close();
        fileInputStream.close();
        log.info("文件下载成功");
    }
}
